package helloworld.example.search;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import helloworld.example.customer.delegate.CustomerListDelegate;
import helloworld.example.customer.delegate.CustomerDelegate;
import helloworld.example.customer.list.CustomerSummaryObject;

public class ManageCustomersAction extends Action {
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		ActionForward forward = null;
		ManageCustomersForm custform = (ManageCustomersForm)form;
		
		if(custform.getSearchButton().isSelected()){
			CustomerListDelegate delegate = new CustomerListDelegate();
			CustomerSummaryObject[] customers = delegate.findCustomers(custform.getLastName());
			request.setAttribute("CUSTOMER_SUMMARY_OBJECTS", customers);
			forward = mapping.findForward("success");
		}
		
		if(custform.getDeleteButton().isSelected()){
			CustomerDelegate delegate = new CustomerDelegate();
			String[] idsToDelete = custform.getIdSelections();
			if (idsToDelete != null && idsToDelete.length > 0 )
			{
				for (int i=0;i<idsToDelete.length;i++)
				{
					int x = Integer.parseInt(idsToDelete[i]);
					delegate.deleteCustomer(x);
				}
			}
			forward = mapping.findForward("deleteSuccess");
		}
		
		if(custform.getNewButton().isSelected()){	
			forward = mapping.findForward("add");
		}
		
		return forward;
	}
}
